package com.lishui.waterojbackendquestionservice.service.impl;

import cn.hutool.http.HttpRequest;
import com.alibaba.nacos.common.utils.CollectionUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.gson.Gson;
import com.lishui.waterojbackendcommon.contant.CommonConstant;
import com.lishui.waterojbackendcommon.contant.MessageConstant;
import com.lishui.waterojbackendcommon.exception.BusinessException;
import com.lishui.waterojbackendcommon.exception.ParameterException;
import com.lishui.waterojbackendcommon.result.PageResult;
import com.lishui.waterojbackendcommon.utils.SqlUtils;
import com.lishui.waterojbackendmodel.model.pojo.dto.QuestionAddDTO;
import com.lishui.waterojbackendmodel.model.pojo.dto.QuestionQueryDTO;
import com.lishui.waterojbackendmodel.model.pojo.dto.QuestionUpdateDTO;
import com.lishui.waterojbackendmodel.model.pojo.entity.JudgeCase;
import com.lishui.waterojbackendmodel.model.pojo.entity.JudgeConfig;
import com.lishui.waterojbackendmodel.model.pojo.entity.Question;
import com.lishui.waterojbackendmodel.model.pojo.entity.User;
import com.lishui.waterojbackendmodel.model.pojo.vo.QuestionVO;
import com.lishui.waterojbackendmodel.model.pojo.vo.UserVO;
import com.lishui.waterojbackendquestionservice.mapper.QuestionMapper;
import com.lishui.waterojbackendquestionservice.service.QuestionService;
import com.lishui.waterojbackendserviceclient.service.UserFeignClient;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.stream.Collectors;


/**
* @author 24197
* @description 针对表【question(题目)】的数据库操作Service实现
* @createDate 2024-04-13 21:17:35
*/
@Service
public class QuestionServiceImpl extends ServiceImpl<QuestionMapper, Question>
    implements QuestionService {
    @Resource
    private UserFeignClient userFeignClient;

    private final static Gson GSON = new Gson();

    /**
     * 校验题目是否合法
     * @param question
     * @param add
     */
    @Override
    public void validQuestion(Question question, boolean add) {
        String title = question.getTitle();
        String content = question.getContent();
        String tags = question.getTags();
        String answer = question.getAnswer();
        String judgeCase = question.getJudgeCase();
        String judgeConfig = question.getJudgeConfig();
        // 创建时，参数不能为空
        if (add) {
            if (StringUtils.isAnyBlank(title, content, tags)) {
                throw new ParameterException(MessageConstant.EMPTY_PARAMETER + ": title|content|tags");
            }
        }
        // 有参数则校验
        if (StringUtils.isNotBlank(title) && title.length() > 80) {
            throw new BusinessException("标题过长");
        }
        if (StringUtils.isNotBlank(content) && content.length() > 8192) {
            throw new BusinessException("内容过长");
        }
        if (StringUtils.isNotBlank(answer) && answer.length() > 8192) {
            throw new BusinessException("答案过长");
        }
        if (StringUtils.isNotBlank(judgeCase) && judgeCase.length() > 8192) {
            throw new BusinessException("判题用例过长");
        }
        if (StringUtils.isNotBlank(judgeConfig) && judgeConfig.length() > 8192) {
            throw new BusinessException("判题配置过长");
        }
    }

    /**
     * 获取查询包装类（用户根据哪些字段查询，根据前端传来的请求对象，得到 mybatis 框架支持的查询 QueryWrapper 类）
     *
     * @param questionQueryDTO
     * @return
     */
    @Override
    public QueryWrapper<Question> getQueryWrapper(QuestionQueryDTO questionQueryDTO) {
        QueryWrapper<Question> queryWrapper = new QueryWrapper<>();
        if (questionQueryDTO == null) {
            return queryWrapper;
        }
        Long id = questionQueryDTO.getId();
        String title = questionQueryDTO.getTitle();
        String content = questionQueryDTO.getContent();
        List<String> tags = questionQueryDTO.getTags();
        String answer = questionQueryDTO.getAnswer();
        Long userId = questionQueryDTO.getUserId();
        String sortField = questionQueryDTO.getSortField();
        String sortOrder = questionQueryDTO.getSortOrder();

        // 拼接查询条件
        queryWrapper.like(StringUtils.isNotBlank(title), "title", title);
        queryWrapper.like(StringUtils.isNotBlank(content), "content", content);
        queryWrapper.like(StringUtils.isNotBlank(answer), "answer", answer);
        if (CollectionUtils.isNotEmpty(tags)) {
            for (String tag : tags) {
                queryWrapper.like("tags", "\"" + tag + "\"");
            }
        }
        queryWrapper.eq(ObjectUtils.isNotEmpty(id), "id", id);
        queryWrapper.eq(ObjectUtils.isNotEmpty(userId), "user_id", userId);
        queryWrapper.orderBy(SqlUtils.validSortField(sortField), sortOrder.equals(CommonConstant.SORT_ORDER_ASC),
                sortField);
        return queryWrapper;
    }


    @Override
    public Long addQuestion(QuestionAddDTO questionAddDTO, HttpServletRequest httpServletRequest) {
        Question question = new Question();
        BeanUtils.copyProperties(questionAddDTO, question);
        List<String> tags = questionAddDTO.getTags();
        if (tags != null) {
            question.setTags(GSON.toJson(tags));
        }
        List<JudgeCase> judgeCase = questionAddDTO.getJudgeCase();
        if (judgeCase != null) {
            question.setJudgeCase(GSON.toJson(judgeCase));
        }
        JudgeConfig judgeConfig = questionAddDTO.getJudgeConfig();
        if (judgeConfig != null) {
            question.setJudgeConfig(GSON.toJson(judgeConfig));
        }
        this.validQuestion(question, true);
        UserVO loginUser = userFeignClient.getCurrentUser(httpServletRequest);
        question.setUserId(loginUser.getId());
        question.setFavourNum(0);
        question.setThumbNum(0);
        boolean result = this.save(question);
        if(!result) throw new BusinessException(MessageConstant.SAVE_EXCEPTION);
        return question.getId();
    }

    @Override
    public void updateQuestion(QuestionUpdateDTO questionUpdateDTO) {
        Question question = new Question();
        BeanUtils.copyProperties(questionUpdateDTO, question);
        List<String> tags = questionUpdateDTO.getTags();
        if (tags != null) {
            question.setTags(GSON.toJson(tags));
        }
        List<JudgeCase> judgeCase = questionUpdateDTO.getJudgeCase();
        if (judgeCase != null) {
            question.setJudgeCase(GSON.toJson(judgeCase));
        }
        JudgeConfig judgeConfig = questionUpdateDTO.getJudgeConfig();
        if (judgeConfig != null) {
            question.setJudgeConfig(GSON.toJson(judgeConfig));
        }
        // 参数校验
        this.validQuestion(question, false);
        long id = questionUpdateDTO.getId();
        // 判断是否存在
        Question oldQuestion = this.getById(id);
        if (oldQuestion == null) throw new BusinessException(MessageConstant.NO_EXISTS + ":question");
        boolean result = this.updateById(question);
        if (!result) throw new BusinessException(MessageConstant.UPDATE_EXCEPTION + ":question");
    }

    @Override
    public QuestionVO getQuestionVO(long id) {
        Question question = this.getById(id);
        if (question == null) {
            throw new BusinessException(MessageConstant.NO_EXISTS + "question");
        }
        QuestionVO questionVO = QuestionVO.objToVo(question);
        // 关联查询用户信息
        Long userId = question.getUserId();
        User user = null;
        UserVO userVO = null;
        if (userId != null && userId > 0) {
            user = userFeignClient.getById(userId);
            userVO = new UserVO();
            BeanUtils.copyProperties(user, userVO);
        }
        questionVO.setUserVO(userVO);
        return questionVO;
    }

    @Override
    public PageResult getQuestionVOPage(QuestionQueryDTO questionQueryDTO) {
        Integer pageNum = questionQueryDTO.getPageNum();
        Integer pageSize = questionQueryDTO.getPageSize();
        QueryWrapper<Question> queryWrapper = this.getQueryWrapper(questionQueryDTO);
        PageHelper.startPage(pageNum, pageSize);
        List<Question> questionList = this.list(queryWrapper);
        PageInfo<Question> pageInfo = new PageInfo<>(questionList);
        List<QuestionVO> questionVOList = questionList.stream()
                .map(question -> getQuestionVO(question.getId()))
                .collect(Collectors.toList());
        return new PageResult(pageInfo.getTotal(), questionVOList);
    }

    @Override
    public void deleteQuestionById(Long id, HttpServletRequest httpServletRequest) {
        Question oldQuestion = this.getById(id);
        UserVO currentUser = userFeignClient.getCurrentUser(httpServletRequest);
        if (oldQuestion == null) throw new BusinessException(MessageConstant.NO_EXISTS + ":question");
        // 仅本人或管理员可删除
        if (!oldQuestion.getUserId().equals(currentUser.getId()) && !userFeignClient.isAdmin(currentUser.getId())) {
            throw new BusinessException(MessageConstant.MISSING_ADMINISTRATOR_RIGHTS);
        }
        boolean b = this.removeById(id);
        if (!b) throw new BusinessException(MessageConstant.REMOVE_EXCEPTION);
    }

    @Override
    public PageResult getQuestionPage(QuestionQueryDTO questionQueryDTO) {
        Integer pageNum = questionQueryDTO.getPageNum();
        Integer pageSize = questionQueryDTO.getPageSize();
        QueryWrapper<Question> queryWrapper = this.getQueryWrapper(questionQueryDTO);
        PageHelper.startPage(pageNum, pageSize);
        List<Question> questionList = this.list(queryWrapper);
        PageInfo<Question> pageInfo = new PageInfo<>(questionList);
        return new PageResult(pageInfo.getTotal(), questionList);
    }

}




